package javase.ch05.homeWork;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPService {
    // 在 TCPService 类中添加静态集合来存储所有客户端连接
    public static List<Socket> clientSockets = Collections.synchronizedList(new ArrayList<>());

    public static void main(String[] args) {
        System.out.println("----------- 我们的世界-Service ------------");
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                3,  //核心线程数
                4,     //最大线程数
                60,       //空闲时间
                TimeUnit.SECONDS, //时间单位
                new ArrayBlockingQueue<>(1), //任务队列（增加队列大小）
                Executors.defaultThreadFactory(), //线程工厂，让线程池如何创建线程对象
                new ThreadPoolExecutor.AbortPolicy() //拒绝策略
        );
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(10086);

            /*System.out.println("成功接入客户端：" + accept.getRemoteSocketAddress());
            InputStream inputStream = accept.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            String string = br.readLine();
            System.out.println("客户端说：" + string);*/

// 在接受新连接时添加客户端到列表
while(true){
    Socket socket = ss.accept();
    clientSockets.add(socket); // 添加新客户端到列表
    System.out.println("新用户来喽：" + socket.getRemoteSocketAddress());
    //使用线程池处理客户端发来的请求
    pool.execute(new MyRunnable(socket));
}


        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            //关闭线程池
            pool.shutdown();
        }
    }
    // 在 TCPService 类中添加广播方法
  public static void broadcastMessage(String message, Socket senderSocket) {
    synchronized (clientSockets) {
        Iterator<Socket> iterator = clientSockets.iterator();
        while (iterator.hasNext()) {
            Socket client = iterator.next();
            try {
                // 不向发送者本人转发消息
                if (client != senderSocket && !client.isClosed() && !client.isOutputShutdown()) {
                    PrintWriter out = new PrintWriter(client.getOutputStream(), true);
                    out.println(message);
                } else if (client.isClosed() || client.isOutputShutdown()) {
                    iterator.remove(); // 移除已关闭的连接
                }
            } catch (IOException e) {
                iterator.remove(); // 移除出错的连接
            }
        }
    }
}

    public static void broadcastMessage(String message) {
        synchronized (clientSockets) {
            Iterator<Socket> iterator = clientSockets.iterator();
            while (iterator.hasNext()) {
                Socket client = iterator.next();
                try {
                    // 不向发送者本人转发消息
                    if ( !client.isClosed() && !client.isOutputShutdown()) {
                        PrintWriter out = new PrintWriter(client.getOutputStream(), true);
                        out.println(message);
                    } else if (client.isClosed() || client.isOutputShutdown()) {
                        iterator.remove(); // 移除已关闭的连接
                    }
                } catch (IOException e) {
                    iterator.remove(); // 移除出错的连接
                }
            }
        }
    }


}
// 修改 MyRunnable 类
class MyRunnable implements Runnable{
    Socket socket;
    String clientName;

    public MyRunnable(Socket socket){
        this.socket = socket;
        this.clientName = socket.getRemoteSocketAddress().toString();
    }

   @Override
public void run() {
    try {
        // 通知所有客户端有新用户加入
        // 广播客户端消息时不向发送者转发
        TCPService.broadcastMessage(clientName + "欢迎" );



        InputStream inputStream = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String message;

        while ((message = br.readLine()) != null) {
            System.out.println("客户端说：" + message);
            // 广播客户端消息
            TCPService.broadcastMessage(clientName + " 说: " + message, socket);

        }
    } catch (Exception e) {
        // 客户端断开连接时的通知
        TCPService.broadcastMessage(clientName + "离开", socket);

    } finally {
        try {
            TCPService.clientSockets.remove(socket); // 从列表中移除
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}





}

